package com.safe.ly_safe.base;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.android.tu.loadingdialog.LoadingDailog;
import com.gyf.barlibrary.ImmersionBar;
import com.safe.ly_safe.R;
import com.safe.ly_safe.utils.CustomLoadDialog;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @PACKAGE :com.safe.ly_safe.base
 * @Author : HSF
 * @Time : On 2022/4/22 15:33
 * @Description : BaseActivity
 */
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity {

    private Unbinder unbinder;

    protected T mPresenter;

    protected ImmersionBar immersionBar;

    protected LoadingDailog mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullScreen();
        setContentView(setContentViewId());
        unbinder = ButterKnife.bind(this);
        mDialog = CustomLoadDialog.createDialog(this,loadingMsg());
        joinTaskStack();     //添加至任务栈
        initImmersionBar();  //初始化沉浸式
        initView();
    }

    //设置全屏--必须在setContentView之前调用
    protected abstract void setFullScreen();

    protected abstract int setContentViewId();

    protected abstract String loadingMsg();

    protected abstract void initView();

    /**
     * 添加进入任务栈
     */
    public void joinTaskStack(){
        BaseApplication.getInstance().joinTaskStack(this);
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        immersionBar = ImmersionBar.with(this);
        immersionBar.barColor(R.color.white).init();
    }

    /**
     * 输入框获取焦点后，弹出软键盘
     * @param editText
     */
    public void getFocus(View editText){
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        editText.findFocus();
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);// 显示输入法
    }

    /**
     * 输入框失去焦点后，隐藏软键盘
     */
    public void lostFocus(){
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        if (immersionBar != null){
            immersionBar.destroy();
        }
        if(mDialog != null && mDialog.isShowing()){
            mDialog.dismiss();
        }
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }
}
